//
//  XLHomeViewController.swift
//  WeiboTT
//
//  Created by 王嘉涛 on 2016/11/12.
//  Copyright © 2016年 王嘉涛. All rights reserved.
//

import UIKit
import YYModel
import SVProgressHUD

private let cellId = "StatusCellId"
private let retweetedCellId = "HMRetweetedStatusCellId"

class XLHomeViewController: XLBaseTableViewController {

    // 控制器该有的模型
    lazy var homeViewModel: HMHomeViewModel = HMHomeViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        if !userLogin {
            //设置访客视图的信息 --> 获取访客视图
            visitorView.updateInfo(title: "come on!欢迎涛哥回来!啦啦啦啦啦啦啦,万万没想到", imageName: "visitordiscover_feed_image_smallicon",isHome: true)
            return
        }
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(push))
        
        setupTableView()
        loadData()
    }
    
    func loadData() {
        
        homeViewModel.loadData(isPullup: indicatorView.isAnimating) { (isSuccess,count) in
            if !isSuccess {
                return
            }
            //需要停止菊花转动 否则只能加载两次数据 (初次+ 第二次)
            self.indicatorView.stopAnimating()
            //停止转动
            self.refreshControl?.endRefreshing()
            
            self.startAnimtaion(count: count)
            self.tableView.reloadData()

        }
    }

    //提示显示多少条数据
    private func startAnimtaion(count: Int) {
        //如果正在做动画就直接返回
        if tipLabel.isHidden == false {
            return
        }
        let tipText = count == 0 ? "没有新微博" : "有\(count)条微博"
        //设置文字
        tipLabel.text = tipText
        //1. 在开始动画前显示tipLabel
        self.tipLabel.isHidden = false
        
        //在开始动画之前记录Y值
        let y = self.tipLabel.frame.origin.y
        UIView.animate(withDuration: 1, animations: {
            //2. 做动画 修改Y值
            self.tipLabel.frame.origin.y = navBarHeight
        }, completion:{ (_) -> () in
            //3. 回去的动画  延迟
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.tipLabel.frame.origin.y = y
            }, completion: { (_) -> () in
                self.tipLabel.isHidden = true
            })
        })
    }

    // 跳转到扫一扫控制器
    @objc private func push(){
        let sweep = XLSweepViewController()
        
        self.navigationController?.pushViewController(sweep, animated: true)
    }

    // 搭建UI
    private func setupTableView(){

        // 注册HMStatusCell
        let statusCellNib = UINib(nibName: "HMStatusCell", bundle: nil)
        tableView.register(statusCellNib, forCellReuseIdentifier: cellId)
        // 注册HMRetweetedStatusCell
        let retweetedCellNib = UINib(nibName: "HMRetweetedStatusCell", bundle: nil)
        tableView.register(retweetedCellNib, forCellReuseIdentifier: retweetedCellId)
        tableView.separatorStyle = .none
        tableView.tableFooterView = indicatorView
        let hmRefreshControl = HMRefreshControl()
        self.view.addSubview(hmRefreshControl)
        
        // 添加tipLabel
        tipLabel.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 35)
        
        // 设置Y值
        tipLabel.frame.origin.y = navBarHeight - 35
        
        // 移动到导航条下面
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)
        
        //设置行高
        tableView.rowHeight = 350
        
    }
    
    // 懒加载小菊花
    internal lazy var indicatorView : UIActivityIndicatorView = {
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        
        return indicator
        
    }()
    
    // 实例化提示加载数据的UILabel控件
    private lazy var tipLabel : UILabel = {
        let l = UILabel(title: "", fontSize: 16, textColor: UIColor.white)
        // 设置背景颜色
        l.backgroundColor = UIColor.orange
        // 设置隐藏
        l.textAlignment = .center
        l.isHidden = true
        return l
    }()
}

extension XLHomeViewController{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.homeViewModel.viewmodelArray.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let viewmodel = self.homeViewModel.viewmodelArray[indexPath.row]
        let Cellid = getCellId(viewmodel: viewmodel)
        let cell = tableView.dequeueReusableCell(withIdentifier: Cellid, for: indexPath) as! HMStatusCell
        cell.viewmodel = viewmodel
        return cell
    }

    // 如果在这里完成控件UI的刷新,这就是强耦合
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }
    
    // 调用行高的协议方法
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // 获取Cell
        let viewmodel = self.homeViewModel.viewmodelArray[indexPath.row]
        let name = nibName(viewmodel: viewmodel)
        let cell = UINib(nibName: name, bundle: nil).instantiate(withOwner: nil, options: nil).last as! HMStatusCell
        cell.viewmodel = viewmodel
        // cell是自动布局,设置了数据自动布局并没有立即生效
        cell.layoutIfNeeded()
        
        // 自动设置行高
        return cell.toolBar.frame.maxY
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // 如果显示的是倒数第二个cell, 并且菊花没有转动的时候就开始执行静默加载
        if indicatorView.isAnimating == false && indexPath.row == homeViewModel.viewmodelArray.count - 2 {
            indicatorView.startAnimating()
            // 请求更多数据
            
        }
    }
    
    // 根据数据获取可重用标识符
    //
    // - Parameter viewmodel: 视图模型
    // - Returns: 标识符
    private func getCellId(viewmodel : HMStatusViewModel) -> String{
        return viewmodel.status?.retweeted_status == nil ? cellId : retweetedCellId
    }
    
    private func nibName(viewmodel: HMStatusViewModel) -> String {
        return (viewmodel.status?.retweeted_status == nil) ? "HMStatusCell" : "HMRetweetedStatusCell"
    }
    
}
